package com.usts236.exam5;

import db.Cursor;
import db.DBHelper;
import db.StuInfo.StuTable;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.List;

import db.StuInfo;
import phoneUtil.PhoneDto;
import phoneUtil.PhoneUtil;

public class ListFragment extends Fragment {

    private static SQLiteDatabase mDatabase;

    private List<Student> list_stu = new ArrayList<>();
    private StudentAdapter adapter;
    private EditText editId;
    private EditText editName;
    private EditText editTel;
    private Button btnCommit;
    private  Button btnimport;
    private ListView lvStu;








    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        DBHelper dbHelper = new DBHelper(getContext(),"info.db",null,1);//create  database
        mDatabase= dbHelper.getWritableDatabase();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fglist_layout, container, false);
        //initView(view);
        check(view);
        updateUI();

        return view;
    }

    private void check(View view) {
        //判断是否有权限
        if(ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_CONTACTS},201);
        }else{
            initView(view);;
        }
    }

    private void updateUI() {
        List<Student> students = ListFragment.getStudents();

        if (adapter == null) {
            adapter = new StudentAdapter(students);
            lvStu.setAdapter(adapter);
        } else {
            adapter.setStudents(students);
            adapter.notifyDataSetChanged();
        }
    }
    private void initData() {

    }

    private void initView(View view) {
        editId = (EditText) view.findViewById(R.id.edit_id);
        editName = (EditText) view.findViewById(R.id.edit_name);
        editTel = (EditText) view.findViewById(R.id.edit_tel);
        btnCommit = (Button) view.findViewById(R.id.btn_commit);
        btnimport = view.findViewById(R.id.btn_read);
        lvStu = (ListView) view.findViewById(R.id.lv_stu);




        btnCommit.setOnClickListener(v -> {
            String id = editId.getText().toString();
            String name = editName.getText().toString();
            String tel = editTel.getText().toString();
            editId.setText("");
            editName.setText("");
            editTel.setText("");
            Student student = new Student(id,name,tel);
            list_stu.add(student);
            ContentValues values = getContentValues(student);//添加student
            mDatabase.insert(StuTable.NAME, null, values);
            updateUI();
            //adapter.notifyDataSetChanged();
        });

        btnimport.setOnClickListener(v -> {
            PhoneUtil phoneUtil = new PhoneUtil(getContext());
            List<Student> persons ;
            persons = phoneUtil.getPhone();
            for (Student i: persons
                 ) {
                ContentValues values = getContentValues(i);
                mDatabase.insert(StuTable.NAME,null,values);
                Log.e("phone",i.getStele());
                updateUI();
            }

        });



    }

    //获取学生列表
    public static List<Student> getStudents() {
        List<Student> students = new ArrayList<>();
        Cursor cursor = queryStudents(null, null);
        try {
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                students.add(cursor.getStudent());
                cursor.moveToNext();
            }
        } finally {
            cursor.close();
        }

        return students;
    }


    //遍历学生
    private static Cursor queryStudents(String whereClause, String[] whereArgs) {
        android.database.Cursor cursor = mDatabase.query(
                StuTable.NAME,
                null,
                whereClause,
                whereArgs,
                null,
                null,
                null
        );
        return new Cursor(cursor);
    }




    private class StudentAdapter extends BaseAdapter {
        private TextView tvId;
        private TextView tvName;
        private ImageView imageView;
        private TextView tvTel;
        private ImageButton btnDelete;


        @Override
        public int getCount() {
            return list_stu.size();
        }

        @Override
        public Object getItem(int position) {
            return list_stu.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void setStudents(List<Student> students) {
            list_stu = students;
        }
        public StudentAdapter(List<Student> students) {
            list_stu = students;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_layout, parent, false);
            tvId = (TextView) convertView.findViewById(R.id.tv_id);
            tvName = (TextView) convertView.findViewById(R.id.tv_name);
            imageView = (ImageView) convertView.findViewById(R.id.imageView);

            tvTel = (TextView) convertView.findViewById(R.id.tv_tel);
            btnDelete = (ImageButton) convertView.findViewById(R.id.btn_delete);

            tvId.setText(list_stu.get(position).getSno());
            tvName.setText(list_stu.get(position).getSname());
            tvTel.setText(list_stu.get(position).getStele());
//调用电话
            tvTel.setOnClickListener(v -> {
                String tel = list_stu.get(position).getStele();
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
                startActivity(intent);
            });

            btnDelete.setOnClickListener(v -> {
                String stutel = list_stu.get(position).getStele();
                list_stu.remove(position);
                String cmd = "DELETE FROM " + StuTable.NAME + " WHERE stuTel =  '" + stutel + "'";
                mDatabase.execSQL("DELETE FROM " + StuTable.NAME + " WHERE stuTel =  '" + stutel + "'");//删除信息
                Log.e("delete",cmd);
                updateUI();
                adapter.notifyDataSetChanged();
            });

            return convertView;
        }


    }

    private static ContentValues getContentValues(Student student) {
        ContentValues values = new ContentValues();
        //values.put(StuTable.Cols.UUID, student.getStuUID().toString());

        values.put(StuTable.Cols.SNUMB, student.getSno());
        values.put(StuTable.Cols.SNAME, student.getSname());
        values.put(StuTable.Cols.STEL, student.getStele());

        return values;
    }




  /*  private class Student {
        private String Sno;
        private String Sname;
        private String Stele;

        public Student(String sno, String sname, String stele) {
            Sno = sno;
            Sname = sname;
            Stele = stele;
        }

        public String getSno() {
            return Sno;
        }

        public void setSno(String sno) {
            Sno = sno;
        }

        public String getSname() {
            return Sname;
        }

        public void setSname(String sname) {
            Sname = sname;
        }

        public String getStele() {
            return Stele;
        }

        public void setStele(String stele) {
            Stele = stele;
        }
    }*/


    //Sqlite


}